<!DOCTYPE html>
<html lang="zh">

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
		<title>课程>专业管理</title>
		<link rel="icon" href="favicon.ico" type="image/ico">
		<meta name="author" content="yinqi">
		<link href="css/bootstrap.min.css" rel="stylesheet">
		<link href="css/materialdesignicons.min.css" rel="stylesheet">
		<link rel="stylesheet" href="./css/materialdesign.css" type="text/css">
		<link href="css/style.min.css" rel="stylesheet">
		<link href="css/bootstrap.min.css" rel="stylesheet">
		<link href="css/materialdesignicons.min.css" rel="stylesheet">
		<link href="css/style.min.css" rel="stylesheet">
		<link rel="stylesheet" href="./css/font.css">
		<link rel="stylesheet" href="./css/xadmin.css">
		<script type="text/javascript" src="./lib/layui/layui.js" charset="utf-8"></script>
		<script type="text/javascript" src="./js/xadmin.js"></script>

		<style type="text/css">
			.rightdiv {
				position: absolute;
				width: 83%;
				height: 92%;
				right: -50px;
				list-style: none;
			}
			.a{
				width: 80%;
			}
			.label-width{
			}
		</style>
	</head>

	<body>
		<div>
			<h3>课程管理>章节管理</h3><br />
			<h3>当前课程名称：<span id="cName"></span> </h3>
		</div><br /><br />
		<!--树形图显示区域-->
		<div clas="divcss5">
			<div class="col-xs-2">
				<ul id="ztree1" class="ztree"></ul><br /><br />
				<button type="button" class="layui-btn" id="addZtree" onclick="addZtree()">新增节点</button><br /><br />
				<button type="button" class="layui-btn" id="empty" onclick="empty()">取消选中</button>
			</div>

			<input type="hidden" id="second" />
		</div>

		<!-- 点击树形图后显示区域 -->
		<div class="layui-fluid, rightdiv" id="editSubject" style="display: none;">
			<div class="layui-row" id="app">
				<form class="layui-form" enctype="multipart/form-data">
					<input type="hidden" id="kpointId" />

					<div class="layui-form-item">
						<label for="username" class="layui-form-label">
                        	<span class="x-red">*</span>课程名称</label>
						<div class="layui-input-inline">
							<input type="text" id="name" lay-verify="required" autocomplete="off" class="layui-input">
						</div>
					</div>

					<div class="layui-form-item">
						<label for="username" class="layui-form-label">                            
							<span class="x-red">*</span>课程类型</label>
						<div class="layui-input-inline">
							<input type="text" readonly="readonly" id="kpointType" lay-verify="required" autocomplete="off" class="layui-input">
						</div>
					</div>
					
					<div class="layui-form-item">
						<label   class="layui-form-label">
                            <span class="x-red">*</span>添加教师</label>
						<div class="layui-input-inline">
							<table id="tb"></table>
							<a href="#" id="check_tea" >选择教师</a>
						</div>
					</div>

					<div class="layui-form-item">
						<label for="username" class="layui-form-label">                            
							<span class="x-red">*</span>视频地址</label>
						<div class="layui-input-inline">
							<input type="text" readonly="readonly" id="VideoName" lay-verify="required" autocomplete="off" class="layui-input">
						</div>
					</div>

					<label for="username" class="layui-form-label">                            
						<span class="x-red">*</span>视频上传
					</label>

					<button type="button" class="layui-btn layui-btn-normal" id="fileList">选择文件</button>
					<div class="layui-upload-list">
						<table class="layui-table a">
							<thead>
								<tr>
									<th>文件名</th>
									<th>大小</th>
									<th>上传进度</th>
									<th>状态</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody id="demoList"></tbody>
						</table>
					</div>
					<button type="button" class="layui-btn" id="fileListAction">开始上传</button>
			</div>

			<div class="layui-form-item">
				<label for="L_repass" class="layui-form-label"></label>
				<button class="layui-btn" lay-filter="add" id="add" type="button" lay-submit="">提交</button>
			</div>

			</form>
		</div>
		</div>

		<script type="text/javascript" src="js/jquery.min.js"></script>
		<script type="text/javascript" src="js/jquery.ztree.all.min.js"></script>
		<script type="text/javascript" src="js/jquery.cookie.js"></script>
		<script src="js/axios.min.js"></script>
		<script>
			layui.use(['laydate', 'form', 'upload', 'element'], function() {
				var laydate = layui.laydate,
					element = layui.element,
					upload = layui.upload,
					form = layui.form;
			
				$(document).on('click', "#check_tea",function(){
					xadmin.open('选择教师', 'course_teacher.html');
				});
				
				//监听提交
				form.on('submit(add)', function(data) {
					axios.defaults.headers.common["token2"] = $.cookie("token2");
					var tr = $("#tb").find("tr");
					var tid = tr.children('td:eq(0)').text();
					if (tid == null || tid==''){
						layer.msg('请为课程添加教师!');
						return;
					}
					if (tr.length > 1){
						layer.msg('当前课程只能添加一位教师!');
						return;
					}
					if($("#VideoName").val() == '') {
						layer.msg('请为课程添加视频!');
						return;
					}
					var eduCourseKpoint = new URLSearchParams();
					eduCourseKpoint.append("kpointId", $("#kpointId").val());
					if($("#kpointType").val() == '视频') {
						eduCourseKpoint.append("kpointType", 0);
					} else if($("#kpointType").val() == '文本') {
						eduCourseKpoint.append("kpointType", 1);
					}
					eduCourseKpoint.append("videoUrl", $("#VideoName").val());
					eduCourseKpoint.append("name", $("#name").val());
					eduCourseKpoint.append("playTime", $("#second").val());
					eduCourseKpoint.append("teacherId", tid);
					var videoName = $("#VideoName").val();
					var str = videoName.split(".");
					var suf = str[str.length - 1];
					eduCourseKpoint.append("videoType", suf);
					axios({
						method: "post",
						url: "http://localhost:9095/admin/kpoint/editEduCourseKpoint",
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						params: eduCourseKpoint
					}).then(function(response) {
						if(response.data.code == 200) {
							layer.alert("章节修改成功！", {
								icon: 6,
								title: "提示",
								offset: "auto",
								skin: 'layui-layer-molv'
							});
						} else {
							layer.alert("章节修改失败！", {
								icon: 5,
								title: "提示",
								offset: "auto",
								skin: 'layui-layer-molv'
							});
						}
					})
				})

				//上传视频
				var xhrOnProgress = function(fun) {
					xhrOnProgress.onprogress = fun; //绑定监听
					//使用闭包实现监听绑
					return function() {
						//通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
						var xhr = $.ajaxSettings.xhr();
						//判断监听函数是否为函数
						if(typeof xhrOnProgress.onprogress !== 'function')
							return xhr;
						//如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
						if(xhrOnProgress.onprogress && xhr.upload) {
							xhr.upload.onprogress = xhrOnProgress.onprogress;
						}
						return xhr;
					}
				}

				var files;
				//多文件列表示例
				var demoListView = $('#demoList'),
					uploadListIns = upload.render({
						elem: '#fileList',
						size: 1024000 //限制文件大小，单位 KB
							,
						exts: "mp3|mp4|avi|asf|3gp|wmv|rmvb" //上传文件类型
							,
						url: "http://localhost:9095/admin/kpoint/setVideo",
						accept: 'file',
						multiple: true,
						auto: false,
						bindAction: '#fileListAction',
						xhr: xhrOnProgress,
						progress: function(value) { //上传进度回调 value进度值
							element.progress('demoList', value + '%') //设置页面进度条
						},
						xhr: function(index, e) {
							console.log("禁用按钮！")
							//当视频开始上传时，禁用上传与提交按钮
							$('#fileListAction').addClass("layui-btn-disabled").attr("disabled", true);
							$('#add').addClass("layui-btn-disabled").attr("disabled", true);

							var percent = e.loaded / e.total; //计算百分比
							percent = parseFloat(percent.toFixed(2));
							element.progress('progress_' + index + '', percent * 100 + '%');
							console.log("-----" + percent);
						},
						choose: function(obj) { //选择文件后执行以下代码
							var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
							//读取本地文件
							obj.preview(function(index, file, result) {
								var tr = $(['<tr id="upload-' + index + '">', '<td>' + file.name + '</td>', '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>', '<td><div class="layui-progress layui-progress-big" lay-filter="progress_' + index + '" lay-showPercent="true"><div class="layui-progress-bar" lay-percent="0%"></div></div></td>', '<td>等待上传</td>', '<td>', '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>', '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>', '</td>', '</tr>'].join(''));
								//单个重传
								tr.find('.demo-reload').on('click', function() {
									obj.upload(index, file);
								});
								//删除
								tr.find('.demo-delete').on('click', function() {
									delete files[index]; //删除对应的文件
									tr.remove();
									uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
								});
								demoListView.append(tr);
							});
						},
						done: function(res, index, upload) { //上传完成，成功或失败
							console.log(res)
							if(res.code == 200) { //上传成功
								//上传成功后，启用按钮
								$('#fileListAction').removeClass("layui-btn-disabled").attr("disabled", false);
								$('#add').removeClass("layui-btn-disabled").attr("disabled", false);
								var tr = demoListView.find('tr#upload-' + index),
									tds = tr.children();
								tds.eq(3).html('<span style="color: #5FB878;">上传成功</span>');
								tds.eq(4).html(''); //清空操作
								//上传成功后，给视频地址重新复制
								$("#VideoName").prop('value', res.data.fileUploadResult.name);
								//上传成功后,把后台返回的时长赋值给隐藏框
								$("#second").prop('value', res.data.seconds);
								return delete this.files[index]; //删除文件队列已经上传成功的文件
							} else if(res.code == -1) {
								layer.msg(res.msg);
							}
							this.error(index, upload);
						},
						error: function(index, upload) {
							var tr = demoListView.find('tr#upload-' + index),
								tds = tr.children();
							tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
							tds.eq(4).find('.demo-reload').removeClass('layui-hide'); //显示重传
						}
					});
			});
		</script>

		<script type="text/javascript">
			var count = 0;
			$(function() {
				onLoadZTree();
			})

			var ztreeId = -1; //用来存储所选中的节点ID
			//用来判断是否为父节点
				//-1:未进行选中,添加父节点
				// 0:选中的是父节点,添加子节点
				// 1:选中的是子节点,无法进行添加
			var parentId = -1; 
			var zTreeObj;
			var setting = {
				view: {
					enable: true,
					showLine: true,
					removeHoverDom: removeHoverDom
				},
				async: {
					autoParam: ['pid'],
					url: ''
				},
				isSimpleData: false, //数据是否采用简单 Array 格式，默认false
				treeNodeKey: "id", //在isSimpleData格式下，当前节点id属性
				treeNodeParentKey: "pId", //在isSimpleData格式下，当前节点的父节点id属性
				showLine: true, //是否显示节点间的连线
				callback: {
					onDblClick: OnDblClick,
					beforeRemove: beforeRemove,
					onRename: zTreeOnRename,
					onClick: onClick
				},
				edit: {
					enable: true, //单独设置为true时，可加载修改、删除图标
					editNameSelectAll: true,
				},
				data: {
					simpleData: {
						enable: true,
						idKey: "id",
						pIdKey: "pId",
						system: "system",
						rootPId: "",
						displayStsates: 'none'
					}
				},
				methods: {
					
				}
			};
			function removeHoverDom(treeId, treeNode) {
				$("#diyBtn_" + treeNode.id).unbind().remove();
				$("#diyBtn_space_" + treeNode.id).unbind().remove();
				$("#addBtn_" + treeNode.tId).unbind().remove();
			}


			/*是否点击标志*/
			var clickFlag = null;
			//修改父节点章节事件
			function zTreeOnRename(event, treeId, treeNode, isCancel) {
				axios.defaults.headers.common["token2"] = $.cookie("token2");
				var eduCourseKpoint = new URLSearchParams();
				eduCourseKpoint.append('kpointId', treeNode.id);
				eduCourseKpoint.append('name', treeNode.name);
				axios({
					method: "post",
					url: 'http://localhost:9095/admin/kpoint/editEduCourseKpoint',
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
						params: eduCourseKpoint
				}).then(function(response) {
					if (response.data.code == 200){
						onLoadZTree()
						layer.msg('修改成功', {
							icon: 1,
							time: 1000
						});
						return true;
					} else {
						layer.msg('修改成功', {
							icon: 1,
							time: 1000
						});
						return true;
					}
				})
			}

			//双击事件
			function OnDblClick(event, treeId, treeNode) {
				if(clickFlag) { //取消上次延时未执行的方法
					clickFlag = clearTimeout(clickFlag); //清除定时器，防止第二次点击生效
				}
				var treeObj = $.fn.zTree.getZTreeObj("ztree1");
				var sNodes = treeObj.getSelectedNodes();
				treeObj.expandNode(sNodes, false, false, false, false);
			}
			
			function del(obj) {
				var tr = obj.parentNode.parentNode;
				var tbody = tr.parentNode;
				tbody.removeChild(tr);
			}

			//点击事件
			function onClick(event, treeId, treeNode) {
				$("#tb").html("");
				ztreeId = treeNode.id;
				$.ajax({
					type:"get",
					url:"http://localhost:9095/admin/kpoint/getById",
					async:true,
					data:{
						"kpointId": treeNode.id
					},
					headers: {
						"token2": $.cookie("token2")
					},
					success:function(msg){
						console.log(msg.data.eduCourseKpoint);
						var eduTeacher = msg.data.eduTeacher;
						//获取返回的数据
						var subject = msg.data.eduCourseKpoint;
						if(subject.parentId == 0) { //选中的是父节点则div全部隐藏
							parentId = 0;
							$("#editSubject").hide();
						} else {
							parentId = 1;
							if (eduTeacher!=null){
								var tea = "<tr><td style='display:none'>"+eduTeacher.id+"</td><td>"+eduTeacher.name+"</td><td><a href='#' onclick='del(this)'>删除</a></td></tr>";
								$("#tb").append(tea);
							}
							$("#editSubject").show();
							$("#kpointId").attr('value', subject.kpointId);
							$("#name").prop('value', subject.name);
							$("#VideoName").prop('value', subject.videoUrl);
							$("#second").prop('value', subject.playTime);
							if(subject.kpointType == 1) {
								$("#kpointType").prop('value', "文本");
							} else if(subject.kpointType == 0) {
								$("#kpointType").prop('value', "视频");
							}
						}
					}
				});
			}
			
			//删除节点
			var treeNodes;
			function beforeRemove(treeId, treeNode) {
				if(treeNode.isParent == true) {
					layer.msg('请首先删除子节点', {
						icon: 5,
						time: 1000
					});
					return false;
				}
				layer.confirm('确认要删除吗？', {
						btn: ['确定', '取消']
					}, function(index) {
						$.ajax({
							type: "POST",
							async: false,
							url: "http://localhost:9095/admin/kpoint/delKpoint",
							data: {
								"pid": treeNode.id
							},
							headers: {
								"token2": $.cookie("token2")
							},
							success: function(data) {
								if(data.code == 200) {
									onLoadZTree(); //重新加载，不然再次添加会报错
									layer.msg('删除成功', {
										icon: 1,
										time: 1000
									});
									return true;
								} else {
									onLoadZTree()
									layer.msg(data.message, {
										icon: 5,
										time: 1000
									});
									return false;
								}
							}
						});
						layer.close(index);
					},
					function() { //取消时刷新tree
						onLoadZTree()
						layer.msg('已取消', {
							icon: 6,
							time: 1000
						});
						return false;
					})
			}
			
			//取消节点选中状态
			function empty(){
				parentId = -1;
				ztreeId = -1;
				var treeObj = $.fn.zTree.getZTreeObj("ztree1");
				var nodes = treeObj.getSelectedNodes();
				if (nodes.length>0) { 
				    treeObj.cancelSelectedNode(nodes[0]);
				}
			}
			

			//新增节点
			function addZtree() {
				var id = $.cookie("id");
				if (parentId==1){
					layer.msg('当前节点为子节点,无法进行添加操作', {
						icon: 1,
						time: 1000
					});
					return false;
				}
				layer.prompt({
			        formType: 0,
			        value: '',
			        title: '请输入节点名称'
				}, function(value, index) {
			        if(value.trim().length === 0) {//非空验证
						return false;
			        }
			        layer.close(index);
			        var name = value;
					$.ajax({
						type: "POST",
						async: false,
						url: "http://localhost:9095/admin/kpoint/addZtree",
						data: {
							"courseId": id,
							"name": name,
							"ztreeId": ztreeId
						},
						headers: {
							"token2": $.cookie("token2")
						},
						success: function(data) {
							if(data.code == 200) {
								count++;
								onLoadZTree(); //重新加载，不然再次添加会报错
								$("#cName").append("");
								layer.msg('添加成功', {
									icon: 1,
									time: 1000
								});
							} else {
								onLoadZTree();
								layer.msg('添加失败' + data.msg + '', {
									icon: 5,
									time: 1000
								});
							}
						}
					});
				})
			};
			
			//树形图显示操作
			function onLoadZTree() {
				//获取课程ID
				var id = $.cookie("id");
				$.ajax({
					async: false, //是否异步
					cache: false, //是否使用缓存
					type: 'GET', //请求方式：post
					url: 'http://localhost:9095/admin/kpoint/selectByPrimaryKey', //请求的路径
					data: {
						"id": id
					},
					headers: {
						"token2": $.cookie("token2")
					},
					success: function(msg) {
						console.log(msg)
						if (msg.data.listz.length!=0){
							treeNodes = eval(msg.data.listz); //把后台封装好的简单Json格式赋给treeNodes
						} else {
							var kongShow = "<font color='red' size='5'>当前课程无章节数据</font>";
							$("#editSubject").append(kongShow);
						}
						var courName = "<span>"+msg.data.eduCourse.courseName+"</span>"
						if(count == 0){
							$("#cName").append(courName);
						}
					}
				});
				$.fn.zTree.init($("#ztree1"), setting, treeNodes);
			}
		</script>
	</body>

</html>